package com.cwx.mychat.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * 作者： cwx
 * 时间： 2024/9/20 13:34
 * 版本： 1.0
 * 注释：
 */
@Slf4j
public class HandlerHeartBeat extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("获取ctx = {}",ctx);
        if(evt instanceof IdleStateEvent){
            IdleStateEvent e = (IdleStateEvent) evt;
            if(e.state() == IdleState.READER_IDLE){
                Channel channel = ctx.channel();
                Attribute<String> attr = channel.attr(AttributeKey.valueOf(channel.id().toString()));
                String userId = attr.get();
                log.info("用户：{}心跳超时", userId);
                ctx.close();
            }else if (e.state() == IdleState.READER_IDLE){
                log.info("收到心跳");
                ctx.writeAndFlush("heart");
            }
        }
    }
}
